package com.geekaca.jsp;

import com.geekaca.jsp.pojo.Brand;
import com.geekaca.jsp.pojo.BrandType;
import com.geekaca.jsp.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/addBrand")
public class AddServlet extends HttpServlet {
    // 成员变量
    private BrandService brandService = new BrandService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        System.out.println("Brand servlet...");



        // 获取输入
        String brandName = req.getParameter("brandName");
        String companyName = req.getParameter("companyName");

        String ordered = req.getParameter("ordered");
        Integer orderInt = Integer.valueOf(ordered);

        String brandTypeNo = req.getParameter("brandType");
        Integer type_id = Integer.parseInt(brandTypeNo);

        String description = req.getParameter("description");


        String status = req.getParameter("status");
        Integer statusInt = Integer.parseInt(status);

        StringBuilder msg = new StringBuilder();

        if (brandName == null || "".equals(brandName.trim())) {
            msg.append("品不能为空<br>");
        }

        if (companyName == null || "".equals(companyName.trim())) {
            msg.append("公司名称不能为空<br>");
        }
        if (!"".equals(msg.toString())) {
            String error = msg.toString();
            req.setAttribute("error", error);
            // 请求转发，浏览器地址栏不会变化
            req.getRequestDispatcher("/addBrand.jsp").forward(req, resp);
            return;
        }

        BrandType brandType;

        switch (type_id) {
            case 1:
                brandType = new BrandType(1, 1, "食品");
                break;
            case 2:
                brandType = new BrandType(2, 2, "数码");
                break;
            case 3:
                brandType = new BrandType(3, 3, "文化");
                break;
            default:
                brandType = new BrandType();
        }


        Brand brand = new Brand(null, brandName, companyName, orderInt, description, statusInt, brandType);
        int added = brandService.addBrand(brand);
        if (added > 0) {
            //跳转到查询所有界面
            req.getRequestDispatcher("/brands").forward(req, resp);
        } else {
            PrintWriter writer = resp.getWriter();
            writer.write("<h2>新增错误。。。<h2>");
        }


    }
}
